﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;

/// <summary>
/// FileManager 的摘要说明
/// </summary>
public class ListFileManager : Handler {
	enum ResultState {
		Success,
		InvalidParam,
		AuthorizError,
		IOError,
		PathNotFound
	}

	private int Start;
	private int Size;
	private int Total;
	private ResultState State;
	private String PathToList;
	private String[] FileList;
	private String[] SearchExtensions;

	public ListFileManager(HttpContext context, string pathToList, string[] searchExtensions)
		: base(context) {
		//this.SearchExtensions = searchExtensions.Select(x => x.ToLower()).ToArray();
		this.SearchExtensions = Get_SearchExtensions(searchExtensions); 
		this.PathToList = pathToList;
	}

	public override void Process() {
		try {
			Start = String.IsNullOrEmpty(Request["start"]) ? 0 : Convert.ToInt32(Request["start"]);
			Size = String.IsNullOrEmpty(Request["size"]) ? Config.GetInt("imageManagerListSize") : Convert.ToInt32(Request["size"]);
		} catch (FormatException) {
			State = ResultState.InvalidParam;
			WriteResult();
			return;
		}
		List<string> buildingList = new List<string>();
		try {
			string localPath = Server.MapPath(PathToList);

			//buildingList.AddRange(Directory.GetFiles(localPath, "*", SearchOption.AllDirectories).Where(x => SearchExtensions.Contains(Path.GetExtension(x).ToLower())).Select(x => PathToList + x.Substring(localPath.Length).Replace("\\", "/")));
			//.net2.0不能用Linq语法
			string[] _FilesName = Directory.GetFiles(localPath, "*", SearchOption.AllDirectories);
			foreach (string _s in _FilesName) { //遍历目录的文件名，用来与文件类型对比，不是指定类型的文件则过滤
				foreach (string _sAllowFile in SearchExtensions) {
					if (Path.GetExtension(_s).ToLower() == _sAllowFile) {//如果对比成功，则添加此文件到文件列表中,并跳出循环继续下一条
						buildingList.Add(PathToList + _s.Substring(localPath.Length).Replace("\\", "/"));//将文件路径处理一下再保存
						continue;
					}
				}
			}
			
			Total = buildingList.Count;
			//FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();//OrderBy排序x=>x表示按大小升序排序,Skip分页Start从第几条开始取,Take返回Size条数据
			//.net2.0不能用Linq语法
			buildingList.Sort();//默认排序
			if (20 >= Total) {//如果Total小于或等于20条，则直接取
				FileList = buildingList.ToArray();
			}
			//不能取超过自己范围的数据，否则会抛异常，所以要做判断
			if (Total > Start) { //如果起始条数大于总条数，才继续
				int _overplus = Total - (Start + Size);
				if (0 <= _overplus) { //如果，总数-起始条数+取几条）大于0，则会不会超出范围
					FileList = buildingList.GetRange(Start, Size).ToArray();
				} else { //否则会超出范围
					FileList = buildingList.GetRange(Start, Size + _overplus).ToArray();
				}
			}
		} catch (UnauthorizedAccessException) {
			State = ResultState.AuthorizError;
		} catch (DirectoryNotFoundException) {
			State = ResultState.PathNotFound;
		} catch (IOException) {
			State = ResultState.IOError;
		} finally {
			WriteResult();
		}
	}

	private void WriteResult() {
		LitJson.JsonData _json = new LitJson.JsonData();
		_json["state"] = GetStateString();
		_json["list"] = Get_FileList(FileList);
		_json["start"] = Start.ToString();
		_json["size"] = Size.ToString();
		_json["total"] = Total.ToString();
		this.WriteJson(_json);
	}

	/// <summary>
	/// 文件名英文转为小写字符
	/// </summary>
	/// <param name="_searchExtensions"></param>
	/// <returns></returns>
	private string[] Get_SearchExtensions(string[] _searchExtensions) {
		if (null != _searchExtensions) {
			for (int i = 0, j = _searchExtensions.Length; i < j; i++) {
				_searchExtensions[i] = _searchExtensions[i].ToLower();
			}
		}
		return _searchExtensions;
	}

	/// <summary>
	/// 获取处理成Json格式的文件列表
	/// </summary>
	/// <returns>JsonData对象,是个列表</returns>
	private LitJson.JsonData Get_FileList(string[] _s_FileList) {
		LitJson.JsonData _list = null;
		if (null != _s_FileList) {
			_list = new LitJson.JsonData();
			foreach (string _s in _s_FileList) {
				LitJson.JsonData _item = new LitJson.JsonData();
				_item["url"] = _s;
				_list.Add(_item);
			}
		}
		return _list;
	}

	private string GetStateString() {
		switch (State) {
			case ResultState.Success:
				return "SUCCESS";
			case ResultState.InvalidParam:
				return "参数不正确";
			case ResultState.PathNotFound:
				return "路径不存在";
			case ResultState.AuthorizError:
				return "文件系统权限不足";
			case ResultState.IOError:
				return "文件系统读取错误";
		}
		return "未知错误";
	}
}
